package com.example.smartwaterapi.config;

import com.example.smartwaterapi.filter.IpRateLimitFilter;
import com.example.smartwaterapi.filter.UserRateLimitFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;

/**
 * 限流过滤器配置
 * 管理过滤器的执行顺序和优先级
 */
@Configuration
public class RateLimitFilterConfig {
    
    /**
     * 注册用户限流过滤器
     * 优先级最高，基于用户ID精确限流
     */
    @Bean
    public FilterRegistrationBean<UserRateLimitFilter> userRateLimitFilterRegistration(
            UserRateLimitFilter userRateLimitFilter) {
        
        FilterRegistrationBean<UserRateLimitFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(userRateLimitFilter);
        registration.addUrlPatterns("/api/*");
        registration.setName("userRateLimitFilter");
        registration.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);
        
        return registration;
    }
    
    /**
     * 注册IP限流过滤器
     * 优先级较低，作为兜底防护
     */
    @Bean
    public FilterRegistrationBean<IpRateLimitFilter> ipRateLimitFilterRegistration(
            IpRateLimitFilter ipRateLimitFilter) {
        
        FilterRegistrationBean<IpRateLimitFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(ipRateLimitFilter);
        registration.addUrlPatterns("/api/*", "/");
        registration.setName("ipRateLimitFilter");
        registration.setOrder(Ordered.HIGHEST_PRECEDENCE + 2);
        
        return registration;
    }
}
